package com.doit.day02;

import com.alibaba.fastjson.JSON;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.roaringbitmap.RoaringBitmap;

import java.time.Duration;
import java.util.*;

/**
 * bitmap
 */
public class Exercise_consumer1 {
    public static void main(String[] args) {
        RoaringBitmap bitmap = RoaringBitmap.bitmapOf();
        new Thread(new BitMapThread(bitmap,"event")).start();
        //让他每隔5s返回一次结果
        Timer timer = new Timer();
        timer.schedule(new BitMapTask(bitmap),5000,5000);
    }
}
class BitMapThread implements Runnable{
    private RoaringBitmap bitmap;
    private KafkaConsumer<String, String> consumer;
    public BitMapThread(RoaringBitmap bitmap,String topic){
        //先搞出来一个consumer对象
        Properties props = new Properties();
        props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"linux01:9092");
        props.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());
        props.setProperty(ConsumerConfig.GROUP_ID_CONFIG,"linux01");
        //选配的
        props.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"true");
        props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
        consumer = new KafkaConsumer<String, String>(props);
        //订阅主题
        consumer.subscribe(Arrays.asList(topic));
        this.bitmap = bitmap;
    }

    @Override
    public void run() {

        //消费数据
        while (true){
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofMillis(Long.MAX_VALUE));
            for (ConsumerRecord<String, String> consumerRecord : poll) {
                //consumerRecord.value==> json  {"event":"cbshgIaYCP","guid":629946,"timestamp":1695801045439}
                String value = consumerRecord.value();
                // 解析json串
                EventLog eventLog = JSON.parseObject(value, EventLog.class);
                int guid = eventLog.getGuid();
                //计算uv ==》 创建一个hashset 将所有的guid放进去   set.size()  每隔5s钟输出一次
                bitmap.add(guid);
            }
        }
    }
}

class BitMapTask extends TimerTask{
    private RoaringBitmap bitmap;

    public BitMapTask(RoaringBitmap bitmap) {
        this.bitmap = bitmap;
    }

    @Override
    public void run() {
        //这边写的逻辑是什么？？返回set.size
        System.out.println(System.currentTimeMillis()+",当前的uv是："+bitmap.getCardinality());

    }
}
